package com.corecloud.tools;

import com.jayway.jsonpath.JsonPath;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;


public class OAuth2Utils {
	private static JwtAccessTokenConverter _jwtAccessTokenConverter = null;

	static {
		_jwtAccessTokenConverter = new JwtAccessTokenConverter();
		KeyPair keyPair = new KeyStoreKeyFactory(new ClassPathResource("keystore.jks"), "corecloud".toCharArray())
				.getKeyPair("jwt_key");
		_jwtAccessTokenConverter.setKeyPair(keyPair);
	}

	public synchronized static JwtAccessTokenConverter getJwtAccessTokenConverter() {

		return _jwtAccessTokenConverter;

	}

	/**
	 * 通过token获取账号名
	 * @param at
	 * @return
	 */
	public static String getUserNameByAccessToken(String at) {
		try {
			Jwt jwt = JwtHelper.decode(at);
			String claims=  jwt.getClaims();
			String username = JsonPath.read(claims, "$.user_name");
			return username;
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 通过token获取client_id
	 * @param at
	 * @return
	 */
	public static String getClientIdByAccessToken(String at) {
		try {
			Jwt jwt = JwtHelper.decode(at);
			String claims=  jwt.getClaims();
			String username = JsonPath.read(claims, "$.client_id");
			return username;
		} catch (Exception e) {
			return null;
		}
	}
}
